<template>
  <zsearch v-loading="loading">
      <template #title>
          <span>角色管理</span>
      </template>
      <template #date>
        <el-input class="input-1" v-model="name" placeholder="请输入名称"></el-input>
      </template>
      <template #select>
        
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch" v-jurisdiction="'system:user:role:list'">查询</el-button>
        
      </template>
      <template #opration>
        <el-button class="btn-2" @click="addRole" v-jurisdiction="'system:user:role:save'">添加角色</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='groupData'
          :header-cell-style="{background:'#11b9d0', color:'#fff'}"
          :height="'100%'"
          :isshowOperation="true"
        >
        <template #default="slotScope">
          <el-button type="text" class="operation" @click="handleEditItem(slotScope.rowData, slotScope.index)" v-jurisdiction="'system:user:role:save'">修改</el-button>
          <el-button type="text" class="operation" @click="handleDelItem(slotScope.rowData, slotScope.index)" v-jurisdiction="'system:user:role:del'">删除</el-button>
        </template>
        </ztable>
      </template>
      <template #page>
        <zpage
            :currentPage="current" 
            :total="total" 
            :pageSize="size"
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>

    <!-- 添加/修改 -->
    <zdialog :title="roleTitle" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
      <template #body>
        <div class="flex-wrap">
          <div class="leftToRight-layout">
            <div class="label">
              <span>角色名称</span>
            </div>
            <div class="operations">
              <el-input v-model="roleName"></el-input>
            </div>
          </div>
        </div>
        <el-tree
            ref="treeRoleRef"
            :props="defaultProps"
            :data="treeData"
            show-checkbox
            node-key="id"
            :default-expanded-keys="[]"
              >
            </el-tree>
			</template>
    </zdialog>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, onMounted, watch, nextTick } from 'vue'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdialog from '@components/dialog/dialog.vue'

import useConfgin from './../../../hook/getconfig'
import useRequet, { RespData } from "./../../../hook/network"
import { debounce } from "./../../../utils/debounce"

import useRequest from './../../../hook/request'
import { ElMessage, ElMessageBox } from 'element-plus'


const configID = 549;
export default defineComponent({
  name: 'Role',
  components: {
    ztable,
    zpage,
    zsearch,
    zdialog
  },
  setup() {

    const rowList = useConfgin(configID)
    console.log('角色管理', rowList)
    const request = useRequet({ path: "" });
    let search = reactive({
      name: '',
      roleName: '',
      typeId: '',
      options: [],
      haveZeroCount: false,
      onlyHighPrice: false,
      onlyWarningCount: false,
      loading: false,

      current: 1,
      size: 10,
      total: 0,
      treeData: [],
      treeCheckedList: [],
    })
    const treeRoleRef = ref(null)
    const defaultProps = {
      children: 'children',
      label: 'name',
      isLeaf: 'leaf'
    }
    const data = ref([])
    const groupData = rowList.groupDataList.value;
    //搜索
    const hanledSearch = () => {
      debounceRefresh()
    }

    const handleType = () => {
      console.debug('下拉')
    }

    

    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
		}

    // 添加角色
    const addRole = () => {
      
      if(treeRoleRef.value) {
        (treeRoleRef.value as any).setCheckedKeys([], false)
      }
      roleTitle.value = '添加角色'
      search.typeId = ''
      dialogVisible.value = true
    }

    // 修改角色
    const handleEditItem = async(rowData: any, index: number) => {
      
      let id = rowData.id
      search.typeId = rowData.id
      roleTitle.value = '修改角色'
      search.roleName = rowData.roleName
      dialogVisible.value = true
      // 获取详情

      let result:any = await useRequest(`/company/user/role/roleDetail/${id}`, {}, 'GET');
      if(result.code !== 0) return ElMessage.error('获取角色详情' + result.msg);
          // search.treeCheckedList = JSON.parse(JSON.stringify(result.data.permissionsIds))
          // search.treeCheckedList = []
          
          result.data.permissionsIds.forEach(async(i:number) => {
            await nextTick();
            (treeRoleRef.value as any).setChecked(i, true, false) // 解决回显半选树
          })
          
    }

    // 删除角色
    const handleDelItem = (rowData: any, index: number) => {
      let id = rowData.id
        ElMessageBox.confirm('此操作将永久删除角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          request.sendRequest({
            address: `company/user/role/del/${id}`,
            params: {},
            success: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
              ElMessage.success('删除成功')
              req()
            },
            fail: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg || '删除失败')
            },
            method: "POST",
          })
        }).catch(() => {
          ElMessage({
            type: 'info',
            message: '已取消删除',
          });
        })
    }
    

    const req = () => {
      search.loading = true
      let params = {
        roleName: search.name,
        current: search.current,
        size: search.size,
      }
      useRequest('company/user/role/rolePage', params, 'POST').then((result:any) => {
        if(result.code !== 0) return ElMessage.error('获取角色列表' + result.msg)
        data.value = result.data.records
        search.total = result.data.total
        search.current = result.data.current

        search.loading = false
      }).catch(e => {
        ElMessage.error(e.data)
        console.debug(e)
      })
      
    }

    const debounceRefresh = debounce(req, 1000)
    

    const getTreeList = async() => {
      let result:any = await useRequest('company/user/role/getPermTree', {}, 'GET')
        if(result.code !== 0) return ElMessage.error('获取权限数据' + result.msg)
            search.treeData = result.data
    }

    

    const closeDialog = () => {
      dialogVisible.value = false
      search.roleName = ''
      if(treeRoleRef.value) {
        (treeRoleRef.value as any).setCheckedKeys([], false)
      }
      
    }

    const dialogVisible = ref(false)
    const roleTitle = ref('添加角色')

    const dialogBtnData = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          closeDialog()
				}
      },
      {
        name: '保存',
        func: (data:object) => {
					console.debug('保存',JSON.parse(JSON.stringify(data)))
            // 全选
            let selectAllIds = (treeRoleRef.value as any).getCheckedKeys()
            // 半选
            let haifIds = (treeRoleRef.value as any).getHalfCheckedKeys()
            let permissionsIds = [...haifIds, ...selectAllIds]
            let fieldIds = [] as any
            let tip = ''
            if(roleTitle.value === '添加角色') {
              tip = '添加角色'
            }
            if(roleTitle.value === '修改角色') {
              tip = '修改角色'
            }

            console.log(permissionsIds)
            
            request.sendRequest({
              address: 'company/user/role/save',
              params: {
                id: search.typeId,
                roleName: search.roleName,
                permissionsIds,
                fieldIds
              },
              success: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(tip + resp.msg)
                ElMessage.success(tip + resp.msg)
                closeDialog()
                req()
              },
              fail: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(tip + resp.msg)
                
              },
              method: "POST",
            })
          
				}
      }
    ]

    

    onMounted(async() => {
      await req()
      await getTreeList()
    })
    
    return { 
      data, 
      groupData,
      defaultProps,
      treeRoleRef,
      ...toRefs(search),
      handleEditItem,
      handleDelItem,

      hanledSearch,
      handleCurrentChange,
      handleSizeChange,
      handleType,


      request,

      dialogVisible,
      closeDialog,
      dialogBtnData,

      addRole,
      roleTitle,
    }
  }
})
</script>

<style lang="scss" scoped>

</style>